package org.example.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;


import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import org.example.ResultCode.R;
import org.example.exceptionHandler.GuliException;
import org.example.vod.service.VodService;
import org.example.vod.utils.ConstantVodUtils;
import org.example.vod.utils.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/educed/video")
@CrossOrigin
public class VodController {
    @Autowired
    private VodService vodService;
   //根据视频id获取视频凭证
   @GetMapping("getPlayAuth/{id}")
   public R getPlayAuth(@PathVariable String id){
       try{
           DefaultAcsClient client= InitVodClient.initVodClient(
                   ConstantVodUtils.ACCESS_KEY_ID,
                   ConstantVodUtils.ACCESS_KEY_SECRET
           );
           //2.创建获取视频凭证的request和response
           GetVideoPlayAuthRequest request=new GetVideoPlayAuthRequest();
           request.setVideoId(id);
           GetVideoPlayAuthResponse response=client.getAcsResponse(request);
           //5.从获取到的视频信息中取视频凭证的信息
           String playAuth = response.getPlayAuth();
           return R.ok().data("playAuth", playAuth);
       }catch (Exception e){
           throw new GuliException(20001, "获取视频凭证失败");
       }
   }

    //上传视频到阿里云
    @PostMapping("uploadAlyVideo")
    public R uploadAlyVideo(MultipartFile file) {
        //返回上传视频的id
        String videoId = vodService.uploadAlyVideo(file);
        return R.ok().data("videoId", videoId);
    }
    //删除视频
    //根据视频id删除阿里云中的视频
    @DeleteMapping("removeAlyVideo/{id}")
    public R removeAlyVideo(@PathVariable String id) {
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频id
            request.setVideoIds(id);
            //调用初始化对象方法实现删除
            client.getAcsResponse(request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "删除视频失败");
        }
    }
    //多个视频删除
    @DeleteMapping("delete-batch")
    public R deleteBatch(@PathVariable("videoIdList") List videoIdList){
        vodService.removeMoreAlyVideo(videoIdList);
        return R.ok();
    }


}
